package itu.twitterandro.application;

import java.util.ArrayList;
import java.util.List;

import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class SearchTweetsActivity extends Activity {
	
	Button buttonSearch;
	EditText searchText;
	Context context;
	TwitterAndroActivity androActivity;
	Tweet myTweet;
	static public ArrayList<Tweet> 	myTweets = new ArrayList<Tweet>();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchtweets);

		
		
		// find views by id
		buttonSearch = (Button) findViewById(R.id.buttonSearch);
		searchText = (EditText) findViewById(R.id.searchText);
		context = getApplicationContext();

		// Add listener
		buttonSearch.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
			
				// TODO Auto-generated method stub
				String searchKey = searchText.getText().toString();
				 Twitter twitter = new TwitterFactory().getInstance();
			        try {
			            QueryResult result = twitter.search(new Query(searchKey));
			            List<twitter4j.Tweet> tweets = result.getTweets();
			            for (twitter4j.Tweet tweet : tweets) {
			            	System.out.println("*****************************");
			            	System.out.println(tweet.getFromUser());
			            	System.out.println("*****************************");
			            	myTweet = new Tweet(tweet.getFromUser(), tweet.getText(), 
			            			tweet.getProfileImageUrl(), tweet.getCreatedAt().toString());
			               myTweets.add(myTweet);

			            }
			            System.out.println("Size of myTweets: " + myTweets.size());
			            Intent listSearchIntent = new Intent(SearchTweetsActivity.this, SearchResultActivity.class);
			            startActivity(listSearchIntent);
			        } catch (TwitterException te) {
			            te.printStackTrace();
			            System.out.println("Failed to search tweets: " + te.getMessage());
			            System.exit(-1);
			        }
			}
		});
		
		
	}
}
